package net.ithe.filter;

import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import net.ithe.utils.CurrentHolder;
import net.ithe.utils.JwtUtils;

import java.io.IOException;
@Slf4j
//@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1.获取到请求路径
        String requestURI = request.getRequestURI();
        //2.判断请求路径是否是登录请求则放行
        if (requestURI.contains("/login")){//是否包含
            log.info("登录请求,放行:{}",requestURI);
            filterChain.doFilter(request,response);
            return;
        }
        //3.如果不是获取token
        String token = request.getHeader("token");
        //4.判断token是否为空，如果为空则重定向到登录页面
        if (token == null||token.isEmpty()) {
            log.info("请求头token为空,返回登录页面");
            response.setStatus(401);
            return;
        }
        //5.如果token存在校验失败返回401
        try {
            Claims claims=JwtUtils.parseToken(token);
            Integer empID=Integer.valueOf(claims.get("id").toString());
            CurrentHolder.setCurrentId(empID);
            log.info("当前用户id:{}",empID);
        }catch (Exception e){
            log.info("token校验失败,返回401");
            response.setStatus(401);
            return;
        }
        //6.如果token存在，则校验成功，放行
        log.info("请求头token校验成功,放行");
        filterChain.doFilter(request,response);

        //7.删除
        CurrentHolder.remove();
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
